//
//  CircleCell.m
//  A段项目
//
//  Created by dllo on 16/3/4.
//  Copyright © 2016年 Scott. All rights reserved.
//

#import "CircleCell.h"
#import "Model.h"
#import <UIImageView+WebCache.h>
#import "Fourth.h"
#import "UMSocial.h"
#import <MBProgressHUD.h>
#import "HomePageCell.h"
#import "Person.h"
#import "FMDBDataHandler.h"
#import "TouchFirstView.h"

#import "NetWorkingHandler.h"

#import <DKNightVersion.h>

#define  WIDTH  [UIScreen mainScreen].bounds.size.width

#define HEIGHT mainPictureHeight + 65 + [[self class]heightForIssueText:self.summary.text] + self.thumbnail.bounds.size.height


@interface CircleCell () <UICollectionViewDelegate,UICollectionViewDataSource>

@property (nonatomic, retain) UIImageView *headerImage; //用户头像

@property (nonatomic, retain) UILabel *userName;  //用户名

@property (nonatomic, retain) UILabel *creatTime; //发布时间

@property (nonatomic, retain) UIButton *attent; //关注

@property (nonatomic, retain) UICollectionView *mainPictureCollentionView;

@property (nonatomic, retain) UILabel *summary;  //图片详细信息

@property (nonatomic, retain) UICollectionView *thumbnail; //缩略图.

@property (nonatomic, retain) UIButton *collectButton;  //收藏按钮

@property (nonatomic, retain) UIButton *downLoadButton; //下载按钮

@property (nonatomic, retain) UIButton *shareButton; //分享按钮


@property (nonatomic, retain) NSMutableArray *arrayForModel;

@property (nonatomic, retain) UIView *line; // 分割线.

@property (nonatomic, retain) NSMutableArray *arrPicture;  //用来放 cell 上的照片


@end

@implementation CircleCell

{
    
    
    float mainPictureHeight;
    
    BOOL isCollected;
    
    NSInteger userId;
    
}

- (void)dealloc {
    
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"checkCollect" object:nil];
    
    self.mainPictureCollentionView.delegate = nil;
    
    self.mainPictureCollentionView.dataSource = nil;
    
    self.thumbnail.delegate = nil;
    
    self.thumbnail.dataSource = nil;
    
    [_headerImage release];
    
    [_userName release];
    
    [_creatTime release];
    
    [_attent release];
    
    [_mainPictureCollentionView release];
    
    [_summary release];
    
    [_thumbnail release];
    
    self.thumbnail.delegate = nil;
    
    
    [_arrayForModel release];
    
    [_line release];
    
    [super dealloc];
    
    
    
}

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    
    if (self) {
        
        
        
        self.headerImage = [[UIImageView alloc] init];
        
        [self.contentView addSubview:self.headerImage];
        
        [_headerImage release];
        
        self.userName = [[UILabel alloc] init];
        
        [self.contentView addSubview:self.userName];
        
        [_userName release];
        
        self.creatTime = [[UILabel alloc] init];
        [self.contentView addSubview:self.creatTime];
        
        [_creatTime release];
        
        self.attent = [UIButton buttonWithType:UIButtonTypeCustom];
        
        self.summary = [[UILabel alloc] init];
        
        [self.contentView addSubview:self.summary];
        
        [_summary release];
        
        [self.contentView addSubview:self.attent];
        
        self.collectButton = [UIButton buttonWithType:UIButtonTypeCustom];
        
        [self.contentView addSubview:self.collectButton];
        
        self.shareButton = [UIButton buttonWithType:UIButtonTypeCustom];
        
        [self.contentView addSubview:self.shareButton];
        
        self.downLoadButton = [UIButton buttonWithType:UIButtonTypeCustom];
        
        [self.contentView addSubview:self.downLoadButton];
        
        self.line = [[UIView alloc] initWithFrame:CGRectZero];
        
        [self.contentView addSubview:self.line];
        
        [_line release];
        

#pragma mark -- 创建 collectionView
        
        UICollectionViewFlowLayout  *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        
        flowLayout.scrollDirection = 1;
        
        flowLayout.minimumLineSpacing = 0;
        
        self.mainPictureCollentionView = [[UICollectionView alloc] initWithFrame:self.bounds collectionViewLayout:flowLayout];
        
        self.mainPictureCollentionView.delegate = self;
        
        self.mainPictureCollentionView.dataSource = self;
        
        [self.contentView addSubview:self.mainPictureCollentionView];
        
        
        [self.mainPictureCollentionView registerClass:[HomePageCell class] forCellWithReuseIdentifier:@"pool1"];
        
        
        [flowLayout release];
        
        
        [_mainPictureCollentionView release];
        
    
        
    }
    
    return self;
    
}

- (void)layoutSubviews {
    
    [super layoutSubviews];
    
#pragma mark -- 夜间模式
    
    self.dk_backgroundColorPicker = DKColorWithColors([UIColor colorWithRed:0.66 green:0.78 blue:0.35 alpha:0.8],  [UIColor colorWithRed:52 / 256.f green:52 / 256.f blue:52 / 256.f alpha:1]);
    
    self.userName.dk_textColorPicker = DKColorWithColors([UIColor blackColor], [UIColor whiteColor]);
    
    self.creatTime.dk_textColorPicker = DKColorWithColors([UIColor blackColor], [UIColor whiteColor]);
    
    self.summary.dk_textColorPicker = DKColorWithColors([UIColor blackColor], [UIColor whiteColor]);
    
    
   // self.backgroundColor = [UIColor colorWithRed:0.66 green:0.78 blue:0.35 alpha:0.8];
    
    self.headerImage.frame = CGRectMake(10, 5, 50, 50);
    
    self.headerImage.layer.cornerRadius = 25;
    
    self.headerImage.layer.masksToBounds = YES;
    
    self.headerImage.backgroundColor = [UIColor grayColor];
    
    self.userName.frame = CGRectMake(65, 5, 200, 20);
    
    self.creatTime.frame = CGRectMake(65, 30, 200, 20);
    
    self.attent.frame = CGRectMake(WIDTH - 120, 15, 50, 20);
    
    self.mainPictureCollentionView.frame = CGRectMake(5,60, WIDTH - 10, mainPictureHeight);
    
    self.mainPictureCollentionView.pagingEnabled = YES;
    
    self.mainPictureCollentionView.layer.cornerRadius = 10;
    
    self.mainPictureCollentionView.layer.masksToBounds = YES;
    
#pragma mark -- 功能按钮
    self.shareButton.frame = CGRectMake(WIDTH - 42,HEIGHT + 5, 16, 16);
    
    self.downLoadButton.frame = CGRectMake(WIDTH - 94, HEIGHT + 5, 16, 16);
    
    self.collectButton.frame = CGRectMake(WIDTH - 146, HEIGHT + 5, 16, 16);
    
    
    [self.shareButton addTarget:self action:@selector(shareAction:) forControlEvents:UIControlEventTouchUpInside];
    
    
    
    [self.shareButton setImage:[UIImage imageNamed:@"share"] forState:UIControlStateNormal];
    
    
    [self.collectButton addTarget:self action:@selector(collectAction:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.downLoadButton setImage:[UIImage imageNamed:@"downLoad"] forState:UIControlStateNormal];
    
    [self.downLoadButton addTarget:self action:@selector(downLoadAction:) forControlEvents:UIControlEventTouchUpInside];
    
    
    self.line.frame = CGRectMake(0, HEIGHT + 22, WIDTH, 2);
    
    
    
    self.line.backgroundColor =[UIColor grayColor];
    
    __block typeof(self)weakSelf = self;
    
    [[NSNotificationCenter defaultCenter] addObserverForName:@"checkCollect" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
        
        [weakSelf.mainPictureCollentionView reloadData];
        
        
    }];
    
    
}


#pragma mark -- 按钮的点击方法. 

- (void)shareAction:(UIButton *)button {
   
    
    
    if (self.arrPicture.count != 0) {
        
    
    id object = [self nextResponder];
    
    while (![object isKindOfClass:[Fourth class]]&&object != nil) {
        
        object = [object nextResponder];
        
    }
    
   Fourth *touchView = (Fourth *)object;
    
   UIImage *image = [self.arrPicture objectAtIndex:self.mainPictureCollentionView.contentOffset.x/(WIDTH - 10)];
    
    
    [UMSocialSnsService presentSnsIconSheetView:touchView
                                         appKey:@"507fcab25270157b37000010"
                                      shareText:@"这是我刚浏览的图片,觉得不错,你也看看吧!"
                                     shareImage:image
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToWechatSession,UMShareToDouban,UMShareToWechatTimeline,nil]
                                       delegate:nil];

    
    }
}

- (void)collectAction:(UIButton *)button {
    

        Model  *model = [self.arrayForModel objectAtIndex:self.mainPictureCollentionView.contentOffset.x/(WIDTH - 10)];
    
    UIImage *image = [self.arrPicture objectAtIndex:self.mainPictureCollentionView.contentOffset.x/(WIDTH - 10)];
    
    if (isCollected) {
        
        
        [[FMDBDataHandler shareDataBaseHandler] deleteImage:model.url];
        
        [self.collectButton setImage:[UIImage imageNamed:@"xin"] forState:UIControlStateNormal];
        
        isCollected = NO;
        
    }else {
        
        Person *per = [[Person alloc] init];
        
        per.number = 200;
        
        per.name = model.url;
        
        per.data = UIImageJPEGRepresentation(image, 1);
        
        [[FMDBDataHandler shareDataBaseHandler] insertInfo:per];
        
        
        [per release];
        
        [self.collectButton setImage:[UIImage imageNamed:@"redXin"] forState:UIControlStateNormal];
        
        isCollected = YES;
        
        
    }
    
}

- (void)downLoadAction:(UIButton *)button {
    
    if (self.arrPicture.count != 0) {
        
        
        id object = [self nextResponder];
        
        while (![object isKindOfClass:[Fourth class]]&&object != nil) {
            
            object = [object nextResponder];
            
        }
        
        Fourth *touchView = (Fourth *)object;

    
     UIImage *image = [self.arrPicture objectAtIndex:self.mainPictureCollentionView.contentOffset.x/(WIDTH - 10)];
    
    /**MBProgress 控件. */
    [MBProgressHUD showHUDAddedTo:touchView.view animated:YES];
        
        __block typeof(self)weakSelf = self;
    dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
        
        UIImageWriteToSavedPhotosAlbum(image,weakSelf, @selector(image: didFinishSavingWithError: contextInfo:), nil);
        
        
        });
    
}
    
}


/*图片保存成功. */
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    if (self.arrPicture.count != 0) {
        
        
        id object = [self nextResponder];
        
        while (![object isKindOfClass:[Fourth class]]&&object != nil) {
            
            object = [object nextResponder];
            
        }
        
        Fourth *touchView = (Fourth *)object;

    if(!error){
        
         [MBProgressHUD hideHUDForView:touchView.view animated:YES];
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"保存成功" preferredStyle:1];
        
        [touchView presentViewController:alert animated:YES completion:^{
            
            [alert dismissViewControllerAnimated:YES completion:nil];
            
        }];
        
        
    }else{
        
         [MBProgressHUD hideHUDForView:touchView.view animated:YES];
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"保存失败" preferredStyle:1];
        
        [touchView presentViewController:alert animated:YES completion:^{
            [alert dismissViewControllerAnimated:YES completion:nil];
            
        }];
        
        
    }
}

}
    


#pragma mark -- collection 的代理方法. 

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    
    return self.arrayForModel.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (self.arrayForModel.count != 0) {
        
    Model *model = [self.arrayForModel objectAtIndex:indexPath.item];
    
    if (collectionView == self.mainPictureCollentionView) {
        
        HomePageCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"pool1" forIndexPath:indexPath];
    
        __block typeof(self)weakSelf = self; // 弱引用 self.
        [cell.imageView sd_setImageWithURL:[NSURL URLWithString:model.url] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            
            if (![weakSelf.arrPicture containsObject:image]) {
                
                [weakSelf.arrPicture addObject:image];
            }
            
        }];
        
        return cell;
        
    }else {
        
         HomePageCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"pool2" forIndexPath:indexPath];
        
          [cell.imageView sd_setImageWithURL:[NSURL URLWithString:model.url]];
        
        return cell;
        
    }
    
    
    }
    return nil;
    
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath  {
    
    if (collectionView == self.mainPictureCollentionView) {
        
        CGSize size = self.mainPictureCollentionView.frame.size;
        
        
        return size;
        
        
    }else {
        
        
        return CGSizeMake(50, 50);
    }
    
    
    
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    
    if (collectionView == self.thumbnail) {
        
        [self.mainPictureCollentionView setContentOffset:CGPointMake((WIDTH - 10) * indexPath.item, 0) animated:YES];
      
        id cell = [self.thumbnail cellForItemAtIndexPath:indexPath];
        
        HomePageCell *cell2 = (HomePageCell *)cell;
        
        cell2.imageView.layer.borderWidth = 2;
        
        cell2.imageView.layer.masksToBounds = YES;
        
        cell2.imageView.layer.borderColor =[[UIColor blueColor]CGColor];
        
    }else {
        
         TouchFirstView *touch = [[TouchFirstView alloc] init];
        
        __block typeof(self)weakSelf = self;
        [NetWorkingHandler netWorkingWithUrl:[NSString stringWithFormat:@"http://mapp.tiankong.com/imageUser/list?pageNum=1&pageSize=50&userId=%ld",userId] complete:^(id result) {
            
    
            NSDictionary *dic = [result objectForKey:@"data"];
            
            NSArray *array = [dic objectForKey:@"list"];
            
            touch.array = [NSMutableArray arrayWithArray:array];
        
            id object = [weakSelf nextResponder];
            
            while (![object isKindOfClass:[Fourth class]]) {
                
                object = [object nextResponder];
                
            }
            Fourth *fourth = (Fourth *)object;
            
            touch.modalPresentationStyle = 2;
            
            [fourth presentViewController:touch animated:YES completion:nil];
            
            [touch.collectionView reloadData];
            
        }];
        
        [touch release];

        }
        
    
}


- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    
    id cell = [self.thumbnail cellForItemAtIndexPath:indexPath];
    
    HomePageCell *cell2 = (HomePageCell *)cell;
    
    cell2.imageView.layer.borderWidth = 0;
    
    cell2.imageView.layer.masksToBounds = YES;
    
    cell2.imageView.layer.borderColor =[[UIColor blueColor]CGColor];
    
    
}

- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
    
    Model *model = [self.arrayForModel objectAtIndex:indexPath.item];
    
    NSArray *array = [[FMDBDataHandler shareDataBaseHandler]selectedForNanme:model.url];
    
    
    
    if (array.count == 0) {
       
        [self.collectButton setImage:[UIImage imageNamed:@"xin"] forState:UIControlStateNormal];
       
        isCollected = NO;
        
    }else {
        
        [self.collectButton setImage:[UIImage imageNamed:@"redXin"] forState:UIControlStateNormal];
        
        isCollected = YES;
        
    }
    
    /**判断,当滑动大的 colllectionView 时.缩略图的指示也出现*/
    if (self.mainPictureCollentionView == collectionView) {
        
        
        id cellThumb = [self.thumbnail cellForItemAtIndexPath:indexPath];
        
        HomePageCell *cell2 = (HomePageCell *)cellThumb;
        
        cell2.imageView.layer.borderWidth = 2;
        
        cell2.imageView.layer.masksToBounds = YES;
        
        cell2.imageView.layer.borderColor =[[UIColor blueColor]CGColor];
        
      /**判断如果 缩略图的cell 超出屏幕的话 改变偏移量. */
        if (cell2.frame.origin.x > WIDTH - 60) {
            
            __block typeof(self)weakSelf = self;
            [UIView animateWithDuration:0.2 animations:^{
                
                weakSelf.thumbnail.contentOffset = CGPointMake((indexPath.item - 5) * 50, 0);
                
            }];
            
        }else {
            
             __block typeof(self)weakSelf = self;
            [UIView animateWithDuration:0.2 animations:^{
                
                weakSelf.thumbnail.contentOffset = CGPointMake(0, 0);
                
            }];
        }
        
        
    }else {
        
        if (self.mainPictureCollentionView.contentOffset.y / (WIDTH - 10) != indexPath.item) {
            
            id cellThumb = [self.thumbnail cellForItemAtIndexPath:indexPath];
            
            HomePageCell *cell2 = (HomePageCell *)cellThumb;
            
            cell2.imageView.layer.borderWidth = 0;
            
            cell2.imageView.layer.masksToBounds = YES;

        }
        
    
        
    }
    
    
}


/**当大的 collectionView 的 cell 结束显示当前 cell时,移除缩略图的指示. */
- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
    
    
    
    
    id cellThumb = [self.thumbnail cellForItemAtIndexPath:indexPath];
    
    HomePageCell *cell2 = (HomePageCell *)cellThumb;
    
        cell2.imageView.layer.borderWidth = 0;
        
        cell2.imageView.layer.masksToBounds = YES;
    
   
    
  
}





- (CGFloat)passedInfo:(Model *)modle {
    
    userId = modle.userId;
    
     self.arrPicture = [NSMutableArray array]; //初始化照片数组
    
    self.arrayForModel = [NSMutableArray array];
    
    NSData *data = [modle.content dataUsingEncoding:4]; //将字符串转化为二进制数据.
    
    id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    
    for (NSDictionary *dic in result) {
        
        Model *model1 = [[Model alloc] init];
        
        [model1 setValuesForKeysWithDictionary:dic];
    
        [self.arrayForModel addObject:model1];

        [model1 release];
        
    }
    
    Model *modle10 = [self.arrayForModel firstObject];
    
    NSLog(@"--%@",modle10.url);
    
    

    Model *model2 = [self.arrayForModel firstObject];
    
    mainPictureHeight = WIDTH/model2.width * model2.height;
    
     [self.mainPictureCollentionView reloadData];
    
    self.summary.text = modle.text;
    
    self.summary.font = [UIFont systemFontOfSize:15];
    
    self.summary.frame = CGRectMake(5, mainPictureHeight + 62, WIDTH, [[self class]heightForIssueText:modle.text]);
    
    self.summary.numberOfLines = 0;

    [self.thumbnail removeFromSuperview];
    
    UICollectionViewFlowLayout *thumbLayout = [[UICollectionViewFlowLayout alloc] init];
    
    thumbLayout.scrollDirection = 1;
    
    thumbLayout.minimumLineSpacing = 10;
    
    self.thumbnail = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:thumbLayout];
    
    
    if (self.arrayForModel.count > 1) {
        
        self.thumbnail.dk_backgroundColorPicker = DKColorWithColors( [UIColor colorWithRed:0.66 green:0.78 blue:0.35 alpha:0.8],  [UIColor colorWithRed:52 / 256.f green:52 / 256.f blue:52 / 256.f alpha:1]);
        
        self.thumbnail.delegate = self;
        
        self.thumbnail.dataSource = self;

        
        [self.thumbnail registerClass:[HomePageCell class] forCellWithReuseIdentifier:@"pool2"];
        
        
        self.thumbnail.frame = CGRectMake(5, mainPictureHeight + 65 + [[self class]heightForIssueText:self.summary.text],WIDTH, 50);
        
        [self.contentView addSubview:self.thumbnail];
        
     
    }
    [_thumbnail release];
    
    [thumbLayout release];
    
    
    
#pragma mark -- 功能按钮布局.
    [self.headerImage sd_setImageWithURL:[NSURL URLWithString:[modle.user objectForKey:@"avatar"]]];
    
    self.userName.text = [modle.user objectForKey:@"nickName"];
    
    self.userName.font = [UIFont systemFontOfSize:12];
    
  
    
    
    NSString * timeStampString = modle.creatTime;
    
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[timeStampString doubleValue] / 1000];
    
    
    NSDate *date2 = [NSDate date];
    
    
    NSTimeInterval time = [date2 timeIntervalSinceDate:date]; //距离现在时间多久
    
    
    
    NSInteger count = time/60;
    
    
    /**判断应该显示那个时间单位. */
    if (time < 60) {
        
        self.creatTime.text = @"刚刚";
        
    }else if (time < 3600) {
        
        self.creatTime.text = [NSString stringWithFormat:@"%ld 分钟前发布", count];
        
        
    }else if (time < 3600*24) {
        
        self.creatTime.text = [NSString stringWithFormat:@"%ld 小时前发布", count/60];
        
    }else {
        
        self.creatTime.text = [NSString stringWithFormat:@"%ld 天前发布", count/60/60];
        
    }
    
    
    self.creatTime.font = [UIFont systemFontOfSize:12];
    
#pragma mark -- 初始化数组.
  
    
    return HEIGHT + 25;
    
}


#pragma mark --text 的自定义高度.

+(CGFloat)heightForIssueText:(NSString *)text {
    
    CGRect rect = [text boundingRectWithSize:CGSizeMake(WIDTH - 10, 0) options:1 attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15]} context:nil];
    
    return rect.size.height;
}





- (void)awakeFromNib {
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    
    
    [super setSelected:selected animated:animated];

    
}

@end
